<template>
  <div class="page">
    <div class="page-prev" v-if="pageIndex != 1" @click="prev">上</div>
    <div class="page-prev disabled" v-else>上</div>
    <div class="page-content">
      <div
        class="page-item"
        :class="{ active: item == pageIndex }"
        v-for="item in pageList"
        :key="item"
        @click="change(item)"
      >
        {{ item }}
      </div>
    </div>
    <div class="page-next" v-if="pageIndex != allPage" @click="next">下</div>
    <div class="page-next disabled" v-else>下</div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps } from "vue";
const props = defineProps(["total", "showpage", "shownum"]);

let total = ref(10); //数据总数
let shownum = ref(20); //每页显示十条数据
let showpage = ref(5); //连续出现的页码数为5
let pageIndex = ref(1); //选中的第几页
let pageList = ref([]); //要显示页码的集合
let allPage = ref(11); //页码总数

let next = () => {
  //下一页的点击事件
  pageIndex.value++;
  createPage();
};
let prev = () => {
  //上一页的点击事件
  pageIndex.value--;
  createPage();
};
let change = (item) => {
  pageIndex.value = item;
  createPage();
};
let createPage = () => {
  allPage.value = Math.ceil(props.total / props.shownum); //向上取整
  let start = 1;
  let end = allPage.value > props.showpage ? props.showpage : allPage.value;
  //找到结尾  约束结尾
  let middleNum = Math.ceil(props.showpage / 2); //中间数
  pageList.value.length = 0; //清空集合
  if (middleNum < pageIndex.value) {
    start = pageIndex.value - Math.floor(props.showpage / 2);
    end = pageIndex.value + Math.floor(props.showpage / 2);
  }
  //在末尾的条件  1  >2 - 3+1
  if (pageIndex.value > allPage.value - middleNum + 1) {
    start = allPage.value - props.showpage + 1; //2-5+1 = -2
    end = allPage.value; //结尾 2
  }
  start = start < 1 ? 1 : start; //约束开头
  for (var i = start; i <= end; i++) {
    pageList.value.push(i); //放入页码显示的集合中去
  }
};
onMounted(() => {
  createPage(); //调用
});
</script>
<style lang="less" scoped>
.page {
  display: flex;
  text-align: center;
  line-height: 32px;
  .page-prev,
  .page-next {
    width: 32px;
    height: 32px;
    border: 1px solid gray;
    background: gray;
    color: white;
    margin-right: 5px;
  }
  .disabled {
    background: white;
  }
  .active {
    background: aqua;
  }
  .page-content {
    display: flex;
    .page-item {
      flex: 1;
      width: 32px;
      height: 32px;
      margin-right: 5px;
      border: 1px solid gray;
    }
  }
}
</style>
